﻿using System;
using System.Collections.Generic;
using System.Web.Services.Protocols;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;

namespace MedicWeb.forms.Editors {
    public partial class OrderEdit : SessionPage {

        private Order order;

        protected void Page_Load(object sender, EventArgs e) {
            var year = DateTime.Now.Year;

            string id = Request.QueryString["id"];
            Form.Action = ResolveUrl("~/forms/Editors/OrderEdit.aspx");
            var ms = new MainService();
            if (id != null) {
                Form.Action += "?id=" + id;
                order = ms.LoadOrder(GetSession(), int.Parse(id));
            } else {
                order = new Order();
                order.Content = "";
                order.Date = DateTime.Now;
                order.IsClosed = 0;
                order.Number = "";
                order.ProtocolDate = DateTime.Now;
                order.ProtocolNumber = "";
            }
            if (order.IsClosed == 1) {
                editOrder.CssClass += " disabled";
            }

            bool create = order.Id == 0;
            Doctor[] doctorListByOrder;
            if (!create) {
                doctorListByOrder = ms.GetDoctorListByOrder(GetSession(), order);
            }else {
                doctorListByOrder = new Doctor[0];
            }
            if (!IsPostBack) {

                printMenu.Controls.Add(
                        new HyperLink() {
                            NavigateUrl = ResolveUrl("~/forms/Reports/Order/ReportOrder.aspx?id=" + order.Id),
                            CssClass = "print",
                            Text = "Приказ"
                        });

                printMenu.Controls.Add(
                    new HyperLink()
                    {
                        NavigateUrl = ResolveUrl("~/forms/Reports/Order/DoctorListReport.aspx?id=" + order.Id),
                        CssClass = "print",
                        Text = "Список"
                    });

                tfOrderContent.Text = order.Content;
                tfOrderDate.Text = order.Date.ToShortDateString();
                tfOrderNumber.Text = order.Number;
                tfProtocolDate.Text = order.ProtocolDate != null ? order.ProtocolDate.Value.ToShortDateString() : "";
                tfProtocolNumber.Text = order.ProtocolNumber;
                comboClosed.SelectedValue = "" + order.IsClosed;
                foreach (var doctor in doctorListByOrder) {
                    hfDocInOrder.Value += "," + doctor.Id;
                }
                //PrintTemplate[] printTemplateList = ms.GetPrintTemplateList(GetSession());
                //foreach (var template in printTemplateList) {
                //    comboTemplate.Items.Add(new ListItem(template.Title, "" + template.Id));
                //}
                //comboTemplate.SelectedValue = "" + order.Template.Id;
            }


            string value = hfDocInOrder.Value;
            int[] ints = GetIds(value);
            List<int> ids = new List<int>(ints);

            Doctor[] doctorListNotInOrder = ms.GetDoctorListNotInOrder(GetSession(), year);
            Doctor[] doctorListByNullOrder = ms.GetDoctorListByOrder(GetSession(), new Order());
            List<Doctor> doctors = new List<Doctor>();
            doctors.AddRange(doctorListByNullOrder);
            doctors.AddRange(doctorListNotInOrder);
            doctors.AddRange(doctorListByOrder);
            foreach (var doctor in doctors) {
                if (!ids.Contains(doctor.Id)) {
                    var row = new TableRow();
                    TableCell down = new TableCell();
                    TableCell edit = new TableCell();
                    TableCell fio = new TableCell();
                    TableCell job = new TableCell();
                    TableCell inst = new TableCell();

                    down.Width = 24;
                    edit.Width = 24;
                    down.Controls.Add(new HyperLink() {CssClass = "down", ID = "" + doctor.Id, ClientIDMode = ClientIDMode.Static});
                    edit.Controls.Add(new HyperLink() {CssClass = "edit modal", NavigateUrl = ResolveUrl("~/forms/Editors/DoctorEdit.aspx?id=" + doctor.Id)});
                    fio.Text = doctor.Surname + " " + doctor.Name + " " + doctor.Patronymic;
                    job.Text = doctor.Job.Title;
                    inst.Text = doctor.Institution.Title;

                    row.Cells.Add(down);
                    row.Cells.Add(edit);
                    row.Cells.Add(fio);
                    row.Cells.Add(job);
                    row.Cells.Add(inst);
                    TableDoctors.Rows.Add(row);
                    //LabelBase.Visible = create;
                }
            }
            TableDoctors.CssClass += " scrollable-200";
            TableDocInOrder.CssClass += " scrollable-200";
            //Doctor[] docListByOrder = new Doctor[0];
            //if (!create) {
            //    docListByOrder = ms.GetDoctorListByOrder(GetSession(), order);
            //}
            foreach (var doctor in doctors) {
                if (ids.Contains(doctor.Id)) {
                    var row = new TableRow();
                    var up = new TableCell();
                    TableCell edit = new TableCell();
                    TableCell fio = new TableCell();
                    TableCell job = new TableCell();
                    TableCell inst = new TableCell();

                    up.Width = 24;
                    edit.Width = 24;
                    up.Controls.Add(new HyperLink() {CssClass = "up", ID = "" + doctor.Id, ClientIDMode = ClientIDMode.Static});
                    edit.Controls.Add(new HyperLink() { CssClass = "edit modal", NavigateUrl = ResolveUrl("~/forms/Editors/DoctorEdit.aspx?id=" + doctor.Id) });
                    fio.Text = doctor.Surname + " " + doctor.Name + " " + doctor.Patronymic;
                    job.Text = doctor.Job.Title;
                    inst.Text = doctor.Institution.Title;
                    row.Cells.Add(up);
                    row.Cells.Add(edit);
                    TableCell number = new TableCell();
                    number.Text = "" + doctor.NumberInOrder;
                    row.Cells.Add(number);
                    row.Cells.Add(fio);
                    row.Cells.Add(job);
                    row.Cells.Add(inst);
                    TableDocInOrder.Rows.Add(row);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            bool create = order.Id == 0;
            MainService mainService = new MainService();
            try {
                string value = hfDocInOrder.Value;
                string[] d = tfOrderDate.Text.Split('.');
                order.Date = new DateTime(Convert.ToInt32(d[2]), Convert.ToInt32(d[1]), Convert.ToInt32(d[0]));
                order.Number = tfOrderNumber.Text;
                string[] d1 = tfProtocolDate.Text.Split('.');
                order.ProtocolDate = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d[01]));
                order.ProtocolNumber = tfProtocolNumber.Text;
                order.Content = tfOrderContent.Text;
                order.IsClosed = Convert.ToInt32(comboClosed.SelectedValue);

                //order.Template = new PrintTemplate(){Id = Convert.ToInt32(comboTemplate.SelectedValue),
                //                                    Title = comboTemplate.SelectedItem.Text};

                string s = hfDocInOrder.Value;
                int[] ids = GetIds(s);
                var doctorList = (List<Doctor>) Session["docList"];

                mainService.SetDoctorsToOrder(GetSession(), ids, order);

                if (doctorList != null) {
                    if (!create) {
                        for (int i = 0; i < doctorList.Count; i++) {
                            if (doctorList[i].Order.Id == order.Id) {
                                doctorList[i].Order = new Order();
                            }
                        }
                    }
                    for (int i = 0; i < doctorList.Count; i++) {
                        for (int j = 0; j < ids.Length; j++) {
                            if (doctorList[i].Id == ids[j]) {
                                doctorList[i].Order = order;
                            }
                        }
                    }
                }

                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {

                if (ex.InnerException is SoapException
                    && ((SoapException) ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }
        }

        private static int[] GetIds(string @string) {
            string[] sid = @string.Split(',');

            var ids = new Int32[sid.Length - 1];
            for (int i = 0; i < sid.Length - 1; i++) {
                ids[i] = Convert.ToInt32(sid[i + 1]);
            }
            return ids;
        }
    }
}
